package com.wall.springbootinit.service.impl;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wall.springbootinit.common.ErrorCode;
import com.wall.springbootinit.exception.BusinessException;
import com.wall.springbootinit.mapper.FileMapper;
import com.wall.springbootinit.model.dto.file.UpdateFileDTO;
import com.wall.springbootinit.model.dto.file.UploadByMenuIdDTO;
import com.wall.springbootinit.model.dto.file.UploadFileDTO;
import com.wall.springbootinit.model.entity.Menu;
import com.wall.springbootinit.model.entity.MenuContent;
import com.wall.springbootinit.service.FileService;
import com.wall.springbootinit.service.MenuContentService;
import com.wall.springbootinit.service.MenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import com.wall.springbootinit.model.entity.File;

import javax.annotation.Resource;
import java.io.IOException;

import static java.io.File.separator;

/**
 * @author 33932
 * @description 针对表【sys_file(文件表)】的数据库操作Service实现
 * @createDate 2024-05-19 15:27:39
 */
@Service
@Slf4j
public class FileServiceImpl extends ServiceImpl<FileMapper, File>
        implements FileService {

    @Value("${uploadUrl}")
    private String filesPath;

    private static String fileUrl = "http://localhost:8101";

    @Resource
    private MenuService menuService;

    @Resource
    private MenuContentService menuContentService;

    @Override
    public Long upload(UploadFileDTO uploadFileDTO) {
        MultipartFile file = uploadFileDTO.getFile();
        String filePath = uploadFileDTO.getFilePath();
        String fileDesc = uploadFileDTO.getFileDesc();

        String path = pathProcessing(filePath);
        // 上传文件全路径
        String thisDirectory = filesPath + separator + path;
        if (file.getSize() > 1024 * 1024 * 1024) {
            throw new BusinessException(ErrorCode.FILE_TO_BIG);
        }
        log.error("thisDirectory = filesPath + filePath：" + thisDirectory);

        // 文件的原始名称 aaa.png
        String originalFilename = file.getOriginalFilename();
        log.error("文件名称：" + originalFilename);

        // aaa
        String mainName = FileUtil.mainName(originalFilename);
        log.error("mainName：" + mainName);

        // png
        String extName = FileUtil.extName(originalFilename);
        log.error("extName：" + extName);
        if (!FileUtil.exist(thisDirectory)) {
            // 如果当前文件的父级目录不存在，就创建
            log.error("如果当前文件的父级目录不存在，就创建");
            FileUtil.mkdir(thisDirectory);
        }
        if (FileUtil.exist(thisDirectory + separator + originalFilename)) {
            // 如果当前上传的文件已经存在了，那么这个时候就要重名一个文件名称
            log.error("如果当前上传的文件已经存在了，那么这个时候就要重名一个文件名称");
            originalFilename = mainName + "_" + System.currentTimeMillis() + "." + extName;
        }
        java.io.File saveFile = new java.io.File(thisDirectory + separator + originalFilename);
        try {
            log.error("存储文件到本地的磁盘里面去");
            // 存储文件到本地的磁盘里面去
            file.transferTo(saveFile);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        File file1 = File.builder()
                .fileName(mainName)
                .filePath(path)
                .fileDesc(fileDesc)
                .fileName(originalFilename)
                .build();
        boolean save = this.save(file1);
        if (!save) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        return file1.getBusinessId();
    }

    @Override
    public String pathProcessing(String filePath) {
        String path = "";
        String os = System.getProperty("os.name");
        //Windows操作系统
        if (os != null && os.toLowerCase().startsWith("windows")) {
            if (filePath != null) {
                if ("/".equals(String.valueOf(filePath.charAt(0)))) {
                    path = filePath.replace("/", "\\");
                    ;
                    log.error("filePath：" + filePath);
                } else {
                    path = separator + filePath;
                    log.error("filePath：" + filePath);
                }
            }
            System.out.printf("当前系统版本是:%s%n", os);
        } else if (os != null && os.toLowerCase().startsWith("linux")) {//Linux操作系统
            System.out.printf("当前系统版本是:%s%n", os);
            if (filePath != null) {
                if ("\\".equals(String.valueOf(filePath.charAt(0)))) {
                    log.error("路径字符串需要处理！");
                    path = filePath.replace("\\", "/");
                } else {
                    path = filePath;
                    log.error("路径字符串不需要处理！");
                }
            }
            log.error("filePath：" + path);
        } else { //其它操作系统
            System.out.printf("当前系统版本是:%s%n", os);
        }
        return path;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        File file = this.getById(id);
        if (file == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        String imagePath = filesPath + file.getFilePath() + separator + file.getFileName();
        log.error("imagePath：" + imagePath);
        java.io.File file1 = new java.io.File(imagePath);
        boolean delete = file1.delete();
        boolean remove = this.removeById(id);
        if (!delete || !remove) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateFile(UpdateFileDTO updateFileDTO) {
        Long id = updateFileDTO.getId();
        String newFileName = updateFileDTO.getNewFileName();
        File file = this.getById(id);
        if (file == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        String imagePath = filesPath + file.getFilePath() + separator + file.getFileName();
        log.error("imagePath：" + imagePath);
        java.io.File file1 = new java.io.File(imagePath);
        String[] name = file.getFileName().split(".");
        boolean rename = file1.renameTo(new java.io.File(filesPath + file.getFilePath() + separator + newFileName + "." + name[1]));
        file.setFileName(newFileName);
        boolean update = this.updateById(file);
        if (!rename || !update) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        return true;
    }

    @Override
    public Boolean uploadByMenuId(UploadByMenuIdDTO uploadByMenuIdDTO) {
        MultipartFile file = uploadByMenuIdDTO.getFile();
        Long menuId = uploadByMenuIdDTO.getMenuId();

        Menu menu = menuService.getById(menuId);
        if (menu == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        UploadFileDTO uploadFileDTO = new UploadFileDTO();
        QueryWrapper<File> fileQueryWrapper = new QueryWrapper<File>().eq("pid", menu.getPid());
        File file1 = this.getOne(fileQueryWrapper);
        uploadFileDTO.setFile(file);
        uploadFileDTO.setFilePath(file1.getFileName());
        Long upload = this.upload(uploadFileDTO);
        if (upload == null){
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        MenuContent menuContent = new MenuContent();
        menuContent.setContent(upload.toString());
        menuContent.setMenuId(menuId);
        boolean save = menuContentService.save(menuContent);
        if (!save){
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        return true;
    }
}




